package cn.itrigger.dynamic.sql.select.render;

import cn.itrigger.dynamic.sql.select.QueryExpressionModel;
import cn.itrigger.dynamic.sql.select.join.JoinCriterion;
import cn.itrigger.dynamic.sql.select.join.JoinModel;
import cn.itrigger.dynamic.sql.select.join.JoinSpecification;
import cn.itrigger.dynamic.sql.structure.BasicColumn;

import static cn.itrigger.dynamic.sql.util.StringUtilities.*;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author admin
 * @date 2018/9/26
 **/
public class JoinRenderer {
    private JoinModel joinModel;
    private QueryExpressionModel queryExpression;

    private JoinRenderer(Builder builder) {
        this.joinModel = Objects.requireNonNull(builder.joinModel);
        this.queryExpression = Objects.requireNonNull(builder.queryExpression);
    }

    public String render() {
        return joinModel.mapJoinSpecifications(this::toRenderedString)
                .collect(Collectors.joining(" "));
    }

    private String toRenderedString(JoinSpecification joinSpecification) {
        return spaceAfter(joinSpecification.getJoinType().shortType())
                + "join"
                + spaceBefore(queryExpression.calculateTableNameIncludingAlias(joinSpecification.getTable()))
                + spaceBefore(renderConditions(joinSpecification));
    }

    private String renderConditions(JoinSpecification joinSpecification) {
        return joinSpecification.mapJoinCriteria(this::renderCriterion)
                .collect(Collectors.joining(" "));
    }

    private String renderCriterion(JoinCriterion joinCriterion) {
        return joinCriterion.getConnector()
                + spaceBefore(applyTableAlias(joinCriterion.getLeftColumn()))
                + spaceBefore(joinCriterion.operator())
                + spaceBefore(applyTableAlias(joinCriterion.getRightColumn()));
    }

    private String applyTableAlias(BasicColumn column) {
        return column.renderWithTableAlias(queryExpression.getTableAliasCalculator());
    }

    public static Builder withJoinModel(JoinModel joinModel) {
        return new Builder().withJoinModel(joinModel);
    }

    public static class Builder {
        private JoinModel joinModel;
        private QueryExpressionModel queryExpression;

        public Builder withJoinModel(JoinModel joinModel) {
            this.joinModel = joinModel;
            return this;
        }

        public Builder withQueryExpression(QueryExpressionModel queryExpression) {
            this.queryExpression = queryExpression;
            return this;
        }

        public JoinRenderer build() {
            return new JoinRenderer(this);
        }
    }
}
